package com.xjl.springbootnetty.netty.init;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName HelloNettyServer
 * @Author xjl
 * @Date 2021/11/16:9:54
 * @Description
 * @Version 1.0.0
 */
@Component
public class HelloNettyServer {


    /**
     * @return a
     * @Author xjl
     * @Description 创建netty 与前端建立长链接
     * @Date 2021/11/1 9:55
     * @Pram a
     */
    @PostConstruct
    public void initNetty() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //这里启动netty客户端
                extracted();
            }
        }).start();


    }

    private void extracted() {
        //创建主线程只负责接收项目
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //创建工作线程负责处理任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //ServerBootstrap 是一个netty的启动器需要
            ServerBootstrap serverNetty = new ServerBootstrap();
            //绑定线程池
            serverNetty.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class) //传入创建channel方式
                    .childHandler(new HelloServerInitializer());  //创建子线程用于处理任务
            //启动服务 绑定端口 设置同步
            ChannelFuture channelFuture = serverNetty.bind(3143).sync();

            //监听关闭channel 设置同步
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
